from django import template
from django.conf import settings

from oracle.base.basemodel import DEFAULT_NAME, DEFAULT_DETAIL, DEFAULT_AVATAR

register = template.Library()


def menu_tree_html(menu_dict, current_menu_id, level=1):
    """
    菜单树的html代码
    先定义html代码，然后向代码中填入参数
    :param menu_dict: 菜单字典
    :param current_menu_id: 当前操作菜单id
    :param level: 当前是第几层菜单
    :return:
    """
    # TODO 根据不同的模板需要进行切换
    # 定义通用菜单html
    # ac active 是否选中菜单
    # l link 链接地址 如果为纯菜单则为#
    # i icon 图标样式，使用font-awesome图标
    # t title 显示标题
    # ar arrow 下拉箭头。如果有子菜单，显示箭头
    # s sub_nav 次菜单项
    html = '<li {ac}><a href="{l}"><i class="fa {i}"></i> <span class="nav-label">{t}</span>{ar}</a>{s}</li>'
    # 根据菜单深度进行匹配对应的html
    if level == 1:
        html = html
    elif level == 2:
        html = f'<ul class="nav nav-second-level collapse">{html}</ul>'
    elif level == 3:
        html = f'<ul class="nav nav-third-level collapse">{html}</ul>'
    else:
        html = f'<ul class="nav nav-third-level collapse">{html}</ul>'

    # 当前操作菜单项
    current_menu = menu_dict.get(current_menu_id)
    # 当前菜单项不存在，返回空值
    if not current_menu:
        return str()
    # 定义是否显示箭头参数
    arrow = ''
    # 是否是当前菜单，是则设置为启用
    current = 'class="active"' if current_menu_id in menu_dict["active"] else ''
    # 是否设置icon
    # TODO 默认icon确认
    icon = current_menu['icon'] if current_menu['icon'] else 'fa-bicycle'
    # sub_nav默认为空
    sub_nav = str()
    # 是否设置url
    if current_menu['url']:
        link = current_menu['url']
    else:
        link = "#"
        # 菜单列表是否有子菜单
        if current_menu['children']:
            # 有子菜单必有箭头指示
            arrow = '<span class="fa arrow"></span>'
            sub_nav = ''
            # 循环子菜单，迭代函数
            for menu_id in current_menu['children']:
                # 获取子菜单html代码
                extend = menu_tree_html(menu_dict, menu_id, level=level + 1)
                sub_nav = f'{sub_nav}{extend}'
            # 如果没有子菜单，则本层没有意义
            if not sub_nav:
                return str()
        else:
            # 没有子菜单，上层菜单存在没有意义
            return str()
    # 格式化html
    return html.format(ac=current, l=link, i=icon, t=current_menu['title'], ar=arrow, s=sub_nav)


# 创建多级菜单
@register.inclusion_tag('oracle/inclusion_tag/left-nav.html', takes_context=True)
def multi_menu(context, request):
    """
    创建多级菜单
    :return:
    """
    # 获取中间件已经处理好的菜单数据
    if hasattr(request, "o_menu"):
        menu_dict = request.o_menu
    else:
        menu_dict = dict()
    # 获取退出url
    logout_url = context["data"].get('logout_url')

    # 定义菜单变量
    nav = str()
    if menu_dict:
        # 构建nav的html代码
        for menu_id in menu_dict['root']['children']:
            extend = menu_tree_html(menu_dict, menu_id)
            nav = f'{nav}{extend}'
    # 用户头像及信息显示
    oracle_user = request.session.get("oracle_user")
    if oracle_user:
        show_name = oracle_user.get("show_name", DEFAULT_NAME)
        show_detail = oracle_user.get("show_detail", DEFAULT_DETAIL)
        show_avatar = oracle_user.get("show_avatar", DEFAULT_AVATAR)
    else:
        show_name, show_detail, show_avatar = DEFAULT_NAME, DEFAULT_DETAIL, DEFAULT_AVATAR
    return {
        'nav': nav,
        'logout_url': logout_url,
        "show_name": show_name,
        "show_detail": show_detail,
        "show_avatar": show_avatar,
    }


# 路径导航
@register.inclusion_tag('oracle/inclusion_tag/breadcrumbs.html')
def menu_breadcrumbs(request):
    """
    路径导航
    :return:
    """
    # 获取中间件处理好的路径导航列表
    if hasattr(request, "o_breadcrumbs"):
        breadcrumbs = request.o_breadcrumbs
    else:
        breadcrumbs = [{"title": "首页", "url": "/", "class": None, }, ]
    breadcrumbs_title = breadcrumbs[1]["title"] if len(breadcrumbs) > 1 else breadcrumbs[0]["title"]
    return {'breadcrumbs': breadcrumbs, 'breadcrumbs_title': breadcrumbs_title}


@register.filter
def has_permission(request, name):
    """
    判断是否有权限，控制粒度到按钮时使用
    :param request:
    :param name: url别名
    :return:
    """
    # 启用权限检测
    if settings.PERMISSION_AUTHENTICATE_ENABLE:
        # url别名是否在获取的权限中
        # 权限是以别名作为key的，所以可以这样直接判断
        if name in request.session.get(settings.PERMISSION_SESSION_KEY, {}):
            return True
    # 未启用直接返回成功
    else:
        return True


@register.simple_tag
def icon_table(column, now_column):
    """
    判断是否为同一组显示内容 专为icon显示页面创建
    :param column: 分组的位置
    :param now_column: 现在的位置
    :return:
    """
    return now_column % column
